package siddur.traktask.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import siddur.traktask.framework.ConfigBean;

@Controller
@RequestMapping("download")
public class DownloadController {

	private static final Logger log4j = Logger.getLogger(DownloadController.class);
	
	@Autowired
	ConfigBean configBean;
	
	@RequestMapping("TaskTracker.crx")
	public void app(HttpServletResponse resp){
		log4j.info("downloading crx");
		
		String filepath = configBean.getConfigValue("app_filepath");
		if(filepath == null){
			filepath = "chrome/TaskTracker.crx";
		}
		File f = new File(filepath);
		if(f.isFile()){
			resp.setHeader("X-Content-Type-Options", "nosniff");
			resp.setHeader("Content-Disposition", "attachment; filename='TaskTracker.crx'");
			resp.setContentLength((int)f.length());
			
			InputStream input = null;
			OutputStream output = null;
			try {
				input = new FileInputStream(f);
				output = resp.getOutputStream();
				IOUtils.copy(input, output);
			} catch (IOException e) {
				resp.setStatus(500);
			} finally {
				IOUtils.closeQuietly(input);
				IOUtils.closeQuietly(output);
			}
			
		}
	}
}
